import { reqUserInfo, reqLogin, reqLogout } from "@/api/user";

import { GET_TOKEN, SET_TOKEN, REMOVE_TOKEN } from "@/utils/Token";

import { loginFormData, loginResponseData, userInfoResponseData } from "@/api/user/type";

import { defineStore } from "pinia";

//路由
import { userState } from "./types";
import { constantRoutes } from "@/router/routes";

const useUserStore = defineStore("user", {
  state: (): userState => ({
    userName: '',
    userPwd: '',
    avatar: '',
    token: GET_TOKEN(),
    menuRoutes: constantRoutes,//左侧菜单数组
  }),
  getters: {
    // getUserName: (state) => state.name,
  },
  actions: {
    async userLogin(data: loginFormData) {
      let result: loginResponseData = await reqLogin(data)

      if (result.code === 200) {
        this.token = result.data!
        //持久化
        SET_TOKEN(result.data!)
        return 'ok'
      } else {
        return Promise.reject(new Error(result.data))
      }
    },

    async getUserInfo() {
      let result: userInfoResponseData = await reqUserInfo()
      const { data } = result
      console.log('返回用户信息', data);
      if (result.code === 200) {
        this.avatar = data.avatar!
        this.userName = data.name!

        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },

    //退出登录
    async userLogout() {

      let result: any = await reqLogout()
      console.log(result);
      if (result.code === 200) {
        this.token = ''
        this.avatar = ''
        this.userName = ''
        REMOVE_TOKEN()
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }

    },
  },
});

export default useUserStore;